package com.eale.inteligentcloud.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.eale.inteligentcloud.common.Result;



/**
 * 文件上传控制器
 * @author Administrator
 *
 */
@Controller
public class FileController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
	
	@RequestMapping("download.do")
	public void download(String fileName, HttpServletResponse response) throws Exception {
		
		File file=new File("D:\\fileUpdate",fileName);
		InputStream in =new FileInputStream(file);
		byte[] temp=new byte[in.available()];
		in.read(temp);
		
		//不同的文件采用不同的格式
		response.setContentType("image/jpg");
		OutputStream out =response.getOutputStream();
		out.write(temp);
		out.flush();
		in.close();
		
		
		
	}
	
	
	@RequestMapping("upfileImage.do")
	public Object upFileImage(@RequestParam("file") MultipartFile file) {
		
		if(null==file) {
			return new Result(1, null, "文件不存在");
		}
		String fileName=file.getOriginalFilename();
		System.out.println("文件名:"+fileName);
		
		String realpath="update";
//		String realPath = request.getServletContext().getRealPath("/updata");
		File path=new File(realpath);
//		File path=new File("D:\\fileUpdate");
		
		if(path.exists()) {
			path.mkdirs();
		}
		
		//构建本地文件,不能直接使用上传的文件名
		//1.使用UUID
		//2.使用MD5
		String[] tempAddr=fileName.split("[.]");
		if(tempAddr.length<2) {
			return new Result(1, null, "文件上传不明确");
		}
		
		File updateFile =new File(path,UUID.randomUUID().toString()+"."+tempAddr[tempAddr.length-1]);
		System.out.println(updateFile.toString());
		
		try {
			//异常处理规则,尽量自己处理
			file.transferTo(updateFile);
			System.out.println("保存成功");
			
			//获取文件名			
			return new Result(1, updateFile.getName(), "保存成功");
			
			
		} catch (IOException e) {
			e.printStackTrace();
			return new Result(1, null, "文件写入异常");
		}
		
		
		
		
	}
}
